<template>
  <div class="admin-activities">
    <div class="page-header">
      <h2>活动管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          添加活动
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索活动名称"
        style="width: 200px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="filterType" placeholder="活动类型" clearable @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option v-for="type in activityTypes" :key="type.value || type" :label="type.label || type" :value="type.value || type" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="活动状态" clearable @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option label="待审核" value="pending" />
        <el-option label="已通过" value="approved" />
        <el-option label="未开始" value="upcoming" />
        <el-option label="进行中" value="ongoing" />
        <el-option label="已结束" value="completed" />
      </el-select>

      <el-select v-model="filterPlatformType" placeholder="活动平台类型" clearable @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option v-for="plat in activityPlatformTypes" :key="plat.value" :label="plat.label" :value="plat.value" />
      </el-select>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleSearch"
      />

      <el-button @click="exportExcel">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredData" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="活动名称" min-width="200" show-overflow-tooltip />
      <el-table-column prop="activityType" label="类型" width="120" />
      <el-table-column prop="activityPlatType" label="活动平台类型" width="140">
        <template #default="{ row }">
          {{ getPlatformTypeLabel(row.activityPlatType) }}
        </template>
      </el-table-column>
      <el-table-column label="时间" width="180">
        <template #default="{ row }">
          {{ row.startTime }} ~ {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="location" label="地点" width="150" show-overflow-tooltip />
      <el-table-column prop="maxParticipants" label="容量" width="100" align="center" />
      <el-table-column prop="currentParticipants" label="报名" width="100" align="center" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="80" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isFeatured" type="success" size="small">推荐</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="primary" link @click="handleRegistrations(row)">
              <el-icon><List /></el-icon>
              报名管理
            </el-button>
            <el-button 
              v-if="hasPermission('activity_approve') && row.status === 'draft'"
              type="success" 
              link 
              @click="handleApprove(row)"
            >
              <el-icon><Check /></el-icon>
              发布
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加活动' : '编辑活动'"
      v-model="dialogVisible"
      width="60%"
    >
      <el-form :model="formData" label-width="100px" :rules="rules">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入活动名称" />
        </el-form-item>

        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="formData.activityType" placeholder="请选择活动类型">
            <el-option
              v-for="type in activityTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="活动平台类型" prop="activityPlatType">
          <el-select v-model="formData.activityPlatType" placeholder="请选择活动平台类型">
            <el-option
              v-for="plat in activityPlatformTypes"
              :key="plat.value"
              :label="plat.label"
              :value="plat.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="活动地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入活动地点" />
        </el-form-item>

        <el-form-item label="最大参与人数" prop="maxParticipants">
          <el-input-number v-model="formData.maxParticipants" :min="1" :max="10000" />
        </el-form-item>

        <el-form-item label="活动海报" prop="posterUrl">
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.posterUrl" :src="formData.posterUrl" class="uploaded-image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="演讲嘉宾" prop="speaker">
          <el-input v-model="formData.speaker" placeholder="请输入演讲嘉宾" />
        </el-form-item>

        <el-form-item label="主办方" prop="organizer">
          <el-input v-model="formData.organizer" placeholder="请输入主办方" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>

        <el-form-item label="是否免费" prop="isFree">
          <el-radio-group v-model="formData.isFree">
            <el-radio :label="true">免费</el-radio>
            <el-radio :label="false">收费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!formData.isFree" label="费用" prop="fee">
          <el-input-number v-model="formData.fee" :min="0" :precision="2" />
        </el-form-item>

        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="published">已发布</el-radio>
            <el-radio label="ongoing">进行中</el-radio>
            <el-radio label="completed">已完成</el-radio>
            <el-radio label="cancelled">已取消</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否推荐" prop="isFeatured">
          <el-switch v-model="formData.isFeatured" />
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 报名管理对话框 -->
    <el-dialog
      title="报名管理"
      v-model="registrationDialogVisible"
      width="70%"
    >
      <div class="registration-header">
        <div>
          <h3>{{ currentActivity?.title }}</h3>
          <p>报名人数：{{ currentActivity?.registrations }}/{{ currentActivity?.capacity }}</p>
        </div>
        <el-button @click="exportRegistrationExcel">导出报名数据</el-button>
      </div>

      <el-table :data="registrationData" style="width: 100%" v-loading="registrationLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="company" label="公司" width="200" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="registrationTime" label="报名时间" width="180" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getRegistrationStatusType(row.status)">
              {{ getRegistrationStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="特殊需求" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.specialRequirements || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.status === 'pending'"
                type="primary"
                link
                @click="confirmRegistration(row)"
              >
                确认
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="warning"
                link
                @click="rejectRegistration(row)"
              >
                拒绝
              </el-button>
              <el-button
                v-if="row.status === 'approved'"
                type="success"
                link
                @click="checkIn(row)"
              >
                签到
              </el-button>
              <el-button type="danger" link @click="cancelRegistration(row)">
                取消
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-section">
        <el-pagination
          v-model:current-page="registrationPage"
          v-model:page-size="registrationPageSize"
          :total="registrationTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRegistrationSizeChange"
          @current-change="handleRegistrationCurrentChange"
        />
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { activityApi } from '@/api/admin'
import {
  Plus,
  Edit,
  Delete,
  Search,
  List,
  Check
} from '@element-plus/icons-vue'
import config from '@/config'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminActivities',
  components: {
    Plus,
    Edit,
    Delete,
    Search,
    List,
    Check
  },
  setup() {
    // 使用导出功能
    const { exportListData, mapperPresets, columnWidthPresets } = useExcelExport()
    
    // 状态
    const loading = ref(false)
    const searchKeyword = ref('')
    const filterType = ref('')
    const filterStatus = ref('')
    const filterPlatformType = ref('')
    const dateRange = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const registrationDialogVisible = ref(false)
    
    const registrationLoading = ref(false)
    const registrationPage = ref(1)
    const registrationPageSize = ref(10)
    const registrationTotal = ref(0)
    const currentActivity = ref(null)
    

    // 活动类型 - 从后端获取
    const activityTypes = ref([])
    
    // 保存状态
    const saving = ref(false)

    // 表单数据
    const formData = reactive({
      title: '',
      activityType: '',
      timeRange: [],
      location: '',
      maxParticipants: 100,
      posterUrl: '',
      description: '',
      speaker: '',
      organizer: '',
      contactPerson: '',
      contactPhone: '',
      activityPlatType: '',
      contactEmail: '',
      isFree: true,
      fee: 0,
      status: 'draft',
      isFeatured: false,
      sortOrder: 0
    })

    // 表单验证规则
    const rules = reactive({
      title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
      activityType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
      timeRange: [{ type: 'array', required: true, message: '请选择活动时间', trigger: 'change' }],
      location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
      maxParticipants: [{ type: 'number', required: true, message: '请输入最大参与人数', trigger: 'blur' }],
      posterUrl: [{ required: true, message: '请上传活动海报', trigger: 'change' }],
      description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
      speaker: [{ required: true, message: '请输入演讲嘉宾', trigger: 'blur' }],
      organizer: [{ required: true, message: '请输入主办方', trigger: 'blur' }],
      contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
      contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
      contactEmail: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
      isFree: [{ required: true, message: '请选择是否免费', trigger: 'change' }],
      fee: [{ type: 'number', min: 0, message: '费用不能为负数', trigger: 'blur' }],
      status: [{ required: true, message: '请选择活动状态', trigger: 'change' }],
      isFeatured: [{ type: 'boolean', message: '请选择是否推荐', trigger: 'change' }],
      sortOrder: [{ type: 'number', min: 0, message: '排序不能为负数', trigger: 'blur' }],
      activityPlatType: [{ required: true, message: '请选择活动平台类型', trigger: 'change' }]
    })

    // 图片上传相关
    const apiConfig = config.getApiConfig()
    const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`)
    const uploadHeaders = ref({
      'token': localStorage.getItem('adminToken') || ''
    })

    // 活动数据列表
    const activitiesList = ref([])

    // 报名数据
    const registrationData = ref([])

    // 过滤后的数据
    const filteredData = computed(() => {
      return activitiesList.value.filter(item => {
        if (searchKeyword.value && !item.title.includes(searchKeyword.value)) return false
        if (filterType.value && item.activityType !== filterType.value) return false
        if (filterStatus.value && item.status !== filterStatus.value) return false
        if (filterPlatformType.value && item.activityPlatType !== filterPlatformType.value) return false
        if (dateRange.value && dateRange.value.length === 2) {
          const start = new Date(dateRange.value[0])
          const end = new Date(dateRange.value[1])
          const activityStart = new Date(item.startTime)
          if (activityStart < start || activityStart > end) return false
        }
        return true
      })
    })

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 'draft':
          return 'info'
        case 'published':
          return 'success'
        case 'ongoing':
          return 'warning'
        case 'completed':
          return 'info'
        case 'cancelled':
          return 'danger'
        default:
          return ''
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'draft':
          return '草稿'
        case 'published':
          return '已发布'
        case 'ongoing':
          return '进行中'
        case 'completed':
          return '已完成'
        case 'cancelled':
          return '已取消'
        default:
          return status
      }
    }

    const platformTypeMappings = [
      { label: '活动日历', value: '活动日历' },
      { label: '行业论坛', value: '行业论坛' },
      { label: '技术交流会', value: '技术交流会' },
      { label: '商务对接会', value: '商务对接会' },
      { label: '产品发布', value: '产品发布' },
      { label: '其他活动', value: '其他活动' }
    ]

    const activityPlatformTypes = ref(platformTypeMappings)

    const getPlatformTypeLabel = (value) => {
      if (!value) return '-'
      const match = platformTypeMappings.find((item) => item.value === value)
      return match ? match.label : value
    }

    // 获取报名状态类型
    const getRegistrationStatusType = (status) => {
      switch (status) {
        case 'pending':
          return 'warning'
        case 'approved':
          return 'success'
        case 'rejected':
          return 'danger'
        case 'attended':
          return 'info'
        default:
          return 'info'
      }
    }

    // 获取报名状态文本
    const getRegistrationStatusText = (status) => {
      switch (status) {
        case 'pending':
          return '待审核'
        case 'approved':
          return '已通过'
        case 'rejected':
          return '已拒绝'
        case 'attended':
          return '已参加'
        case 'cancelled':
          return '已取消'
        case 'completed':
          return '已完成'
        case 'confirmed':
          return '已确认'
        default:
          return status
      }
    }

    // 获取模拟活动数据
    const getMockActivities = () => {
      return [
        {
          id: 1,
          title: '机器人技术创新论坛',
          activityType: 'tech-exchange',
          startTime: '2025-01-15 09:00:00',
          endTime: '2025-01-15 17:00:00',
          location: '深圳会展中心1号馆',
          maxParticipants: 200,
          currentParticipants: 156,
          status: 'published',
          isFeatured: true,
          description: '探讨机器人技术的最新发展趋势',
          speaker: '张教授',
          organizer: '深圳机器人协会',
          contactPerson: '李经理',
          contactPhone: '13800138000',
          contactEmail: 'li@example.com',
          isFree: true,
          fee: 0,
          sortOrder: 1
        },
        {
          id: 2,
          title: '智能制造商务对接会',
          activityType: 'business-matching',
          startTime: '2025-01-16 10:00:00',
          endTime: '2025-01-16 16:00:00',
          location: '深圳会展中心2号馆',
          maxParticipants: 100,
          currentParticipants: 89,
          status: 'ongoing',
          isFeatured: false,
          description: '智能制造企业商务对接交流',
          speaker: '王总',
          organizer: '智能制造联盟',
          contactPerson: '陈经理',
          contactPhone: '13900139000',
          contactEmail: 'chen@example.com',
          isFree: false,
          fee: 500,
          sortOrder: 2
        },
        {
          id: 3,
          title: '新产品发布会',
          activityType: 'product-release',
          startTime: '2025-01-17 14:00:00',
          endTime: '2025-01-17 16:00:00',
          location: '深圳会展中心3号馆',
          maxParticipants: 150,
          currentParticipants: 120,
          status: 'draft',
          isFeatured: true,
          description: '最新机器人产品发布',
          speaker: '刘工程师',
          organizer: '创新科技公司',
          contactPerson: '赵经理',
          contactPhone: '13700137000',
          contactEmail: 'zhao@example.com',
          isFree: true,
          fee: 0,
          sortOrder: 3
        }
      ]
    }

    // 加载活动类型
    const loadActivityTypes = async () => {
      try {
        const response = await activityApi.getActivityTypes()
        if (response.code === '200') {
          activityTypes.value = response.data || []
        } else {
          // 使用默认类型
          activityTypes.value = [
            { label: '技术交流会', value: 'tech-exchange' },
            { label: '商务对接会', value: 'business-matching' },
            { label: '产品发布会', value: 'product-release' },
            { label: '行业论坛', value: 'industry-forum' }
          ]
        }
      } catch (error) {
        console.error('加载活动类型失败:', error)
        // 使用默认类型
        activityTypes.value = [
          { label: '技术交流会', value: 'tech-exchange' },
          { label: '商务对接会', value: 'business-matching' },
          { label: '产品发布会', value: 'product-release' },
          { label: '行业论坛', value: 'industry-forum' }
        ]
      }
    }

    // 加载活动数据
    const loadActivities = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value
        }
        
        if (searchKeyword.value) params.keyword = searchKeyword.value
        if (filterType.value) params.activityType = filterType.value
        if (filterStatus.value) params.status = filterStatus.value
        if (filterPlatformType.value) params.activityPlatType = filterPlatformType.value

        const response = await activityApi.getActivitiesPage(params)
        if (response.code === '200') {
          activitiesList.value = response.data.records || []
          total.value = response.data.total || 0
        } else {
          // 如果API返回错误，使用模拟数据
          activitiesList.value = getMockActivities()
          total.value = activitiesList.value.length
        }
      } catch (error) {
        console.error('加载活动数据失败:', error)
        // 使用模拟数据作为回退
        activitiesList.value = getMockActivities()
        total.value = activitiesList.value.length
        ElMessage.warning('使用模拟数据，请检查后端连接')
      } finally {
        loading.value = false
      }
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      loadActivities()
    }

    // 处理分页
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      loadActivities()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadActivities()
    }

    // 显示添加对话框
    const showAddDialog = () => {
      dialogType.value = 'add'
      Object.assign(formData, {
        title: '',
        activityType: '',
        activityPlatType: '',
        timeRange: [],
        location: '',
        maxParticipants: 100,
        posterUrl: '',
        description: '',
        speaker: '',
        organizer: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        isFree: true,
        fee: 0,
        status: 'draft',
        isFeatured: false,
        sortOrder: 0
      })
      dialogVisible.value = true
    }

    // 处理编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.assign(formData, {
        ...row,
        activityPlatType: row.activityPlatType || '',
        timeRange: row.startTime && row.endTime ? [row.startTime, row.endTime] : []
      })
      dialogVisible.value = true
    }

    // 处理删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这个活动吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        try {
          const response = await activityApi.deleteActivity(row.id)
          if (response.code === '200') {
            ElMessage.success('删除成功')
            loadActivities()
          } else {
            ElMessage.error(response.msg || '删除失败')
          }
        } catch (apiError) {
          // 如果API调用失败，从本地数据中删除
          const index = activitiesList.value.findIndex(item => item.id === row.id)
          if (index > -1) {
            activitiesList.value.splice(index, 1)
            ElMessage.success('删除成功（本地数据）')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除活动失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 处理审核
    const handleApprove = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要发布活动 "${row.title}" 吗？`,
          '确认发布',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        try {
          const response = await activityApi.updateActivityStatus(row.id, 'published')
          if (response.code === '200') {
            ElMessage.success('发布成功')
            loadActivities()
          } else {
            ElMessage.error(response.msg || '发布失败')
          }
        } catch (apiError) {
          // 如果API调用失败，更新本地数据
          const index = activitiesList.value.findIndex(item => item.id === row.id)
          if (index > -1) {
            activitiesList.value[index].status = 'published'
            ElMessage.success('发布成功（本地数据）')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('发布活动失败:', error)
          ElMessage.error('发布失败')
        }
      }
    }

    // 处理上传成功
    const handleUploadSuccess = (response) => {
      if (response && (response.code === '200' || response.code === 200)) {
        formData.posterUrl = response.data.url
        ElMessage.success('图片上传成功!')
      } else {
        ElMessage.error('图片上传失败!')
      }
    }

    // 上传前检查
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 15

      if (!isImage) {
        ElMessage.error('只能上传图片格式的文件!')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过 15MB!')
        return false
      }
      return true
    }

    // 处理提交
    const handleSubmit = async () => {
      try {
        const submitData = {
          ...formData,
          startTime: formData.timeRange[0],
          endTime: formData.timeRange[1]
        }
        delete submitData.timeRange

        try {
          let response
          if (dialogType.value === 'add') {
            response = await activityApi.addActivity(submitData)
          } else {
            response = await activityApi.updateActivity(submitData)
          }

          if (response.code === '200') {
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
            dialogVisible.value = false
            loadActivities()
          } else {
            ElMessage.error(response.msg || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
          }
        } catch (apiError) {
          // 如果API调用失败，更新本地数据
          if (dialogType.value === 'add') {
            const newId = Math.max(...activitiesList.value.map(item => item.id), 0) + 1
            submitData.id = newId
            activitiesList.value.push(submitData)
            ElMessage.success('添加成功（本地数据）')
          } else {
            const index = activitiesList.value.findIndex(item => item.id === submitData.id)
            if (index > -1) {
              activitiesList.value[index] = submitData
              ElMessage.success('更新成功（本地数据）')
            }
          }
          dialogVisible.value = false
        }
      } catch (error) {
        console.error('提交活动失败:', error)
        ElMessage.error('提交失败')
      }
    }

    // 处理报名管理
    const handleRegistrations = (row) => {
      currentActivity.value = row
      registrationDialogVisible.value = true
      loadRegistrations()
    }

    // 格式化报名数据
    const formatRegistrationData = (registrations) => {
      return registrations.map(reg => ({
        id: reg.id,
        name: reg.name,
        company: reg.company,
        position: reg.position,
        phone: reg.phone,
        email: reg.email,
        registrationTime: reg.createdTime,
        status: reg.status === 'approved' ? 'confirmed' : reg.status,
        specialRequirements: reg.specialRequirements,
        auditComment: reg.auditComment,
        auditTime: reg.auditTime,
        checkInTime: reg.checkInTime
      }))
    }

    // 加载报名数据
    const loadRegistrations = async () => {
      if (!currentActivity.value) return
      
      registrationLoading.value = true
      try {
        const response = await activityApi.getActivityRegistrations(currentActivity.value.id, {
          page: registrationPage.value,
          size: registrationPageSize.value
        })
        if (response.code === '200') {
          const registrations = response.data.records || []
          registrationData.value = formatRegistrationData(registrations)
          registrationTotal.value = response.data.total || 0
        } else {
          ElMessage.error(response.msg || '加载报名数据失败')
          registrationData.value = []
          registrationTotal.value = 0
        }
      } catch (error) {
        console.error('加载报名数据失败:', error)
        ElMessage.error('加载报名数据失败')
        registrationData.value = []
        registrationTotal.value = 0
      } finally {
        registrationLoading.value = false
      }
    }

    // 确认报名
    const confirmRegistration = async (row) => {
      try {
        const response = await activityApi.confirmRegistration(row.id)
        if (response.code === '200') {
          ElMessage.success('确认成功')
          loadRegistrations()
        } else {
          ElMessage.error(response.msg || '确认失败')
        }
      } catch (error) {
        console.error('确认报名失败:', error)
        ElMessage.error('确认失败')
      }
    }

    // 取消报名
    const cancelRegistration = async (row) => {
      try {
        await ElMessageBox.confirm(
          '确定要取消这个报名吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await activityApi.cancelRegistration(row.id)
        if (response.code === '200') {
          ElMessage.success('取消成功')
          loadRegistrations()
        } else {
          ElMessage.error(response.msg || '取消失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消报名失败:', error)
          ElMessage.error('取消失败')
        }
      }
    }

    // 报名分页处理
    const handleRegistrationSizeChange = (val) => {
      registrationPageSize.value = val
      registrationPage.value = 1
      loadRegistrations()
    }

    const handleRegistrationCurrentChange = (val) => {
      registrationPage.value = val
      loadRegistrations()
    }

    // 拒绝报名
    const rejectRegistration = async (row) => {
      try {
        const { value: reason } = await ElMessageBox.prompt(
          '请输入拒绝原因',
          '拒绝报名',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '请输入拒绝原因...'
          }
        )
        
        const response = await activityApi.rejectRegistration(row.id, reason)
        if (response.code === '200') {
          ElMessage.success('拒绝成功')
          loadRegistrations()
        } else {
          ElMessage.error(response.msg || '拒绝失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝报名失败:', error)
          ElMessage.error('拒绝失败')
        }
      }
    }

    // 签到
    const checkIn = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要为 ${row.name} 签到吗？`,
          '确认签到',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await activityApi.checkIn(row.id)
        if (response.code === '200') {
          ElMessage.success('签到成功')
          loadRegistrations()
        } else {
          ElMessage.error(response.msg || '签到失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('签到失败:', error)
          ElMessage.error('签到失败')
        }
      }
    }

    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      if (userInfo.permissions?.includes('all')) return true
      return userInfo.permissions?.includes(permission) || false
    }

    // 导出活动列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = {
          page: 1,
          size: 1000000,
          keyword: searchKeyword.value || '',
          activityType: filterType.value || '',
          status: filterStatus.value || '',
          startDate: dateRange.value?.[0] || '',
          endDate: dateRange.value?.[1] || ''
        }
        const response = await activityApi.getActivitiesPage(params)
        return response.data.records
      }

      // 数据映射函数
      const mapData = (item) => ({
        'ID': mapperPresets.handleEmpty(item.id),
        '活动名称': mapperPresets.handleEmpty(item.title),
        '活动类型': mapperPresets.handleEmpty(item.activityType),
        '开始时间': mapperPresets.handleEmpty(item.startTime),
        '结束时间': mapperPresets.handleEmpty(item.endTime),
        '活动地点': mapperPresets.handleEmpty(item.location),
        '最大参与人数': mapperPresets.handleEmpty(item.maxParticipants),
        '当前报名人数': mapperPresets.handleEmpty(item.currentParticipants),
        '活动状态': getStatusText(item.status),
        '是否推荐': item.isFeatured ? '是' : '否',
        '主讲人': mapperPresets.handleEmpty(item.speaker),
        '主办方': mapperPresets.handleEmpty(item.organizer),
        '联系人': mapperPresets.handleEmpty(item.contactPerson),
        '联系电话': mapperPresets.handleEmpty(item.contactPhone),
        '联系邮箱': mapperPresets.handleEmpty(item.contactEmail),
        '活动平台类型': mapperPresets.handleEmpty(getPlatformTypeLabel(item.activityPlatType)),
        '是否免费': item.isFree ? '免费' : '收费',
        '费用': item.isFree ? '-' : mapperPresets.handleEmpty(item.fee),
        '排序': mapperPresets.handleEmpty(item.sortOrder),
        '创建时间': mapperPresets.handleEmpty(item.createdTime)
      })

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        '活动列表',
        columnWidthPresets.activity,
        '活动列表'
      )
    }

    // 导出报名数据
    const exportRegistrationExcel = async () => {
      if (!currentActivity.value) {
        ElMessage.warning('请先选择活动')
        return
      }

      // 获取数据的函数
      const fetchData = async () => {
        const params = {
          page: 1,
          size: 1000000,
          activityId: currentActivity.value.id
        }
        const response = await activityApi.getActivityRegistrations(currentActivity.value.id, params)
        return response.data.records
      }

      // 数据映射函数
      const mapData = (item) => ({
        'ID': mapperPresets.handleEmpty(item.id),
        '姓名': mapperPresets.handleEmpty(item.name),
        '公司': mapperPresets.handleEmpty(item.company),
        '职位': mapperPresets.handleEmpty(item.position),
        '电话': mapperPresets.handleEmpty(item.phone),
        '邮箱': mapperPresets.handleEmpty(item.email),
        '报名时间': mapperPresets.handleEmpty(item.createdTime),
        '状态': getRegistrationStatusText(item.status),
        '特殊需求': mapperPresets.handleEmpty(item.specialRequirements)
      })

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        `${currentActivity.value.title}-报名数据`,
        columnWidthPresets.registration,
        `${currentActivity.value.title}-报名数据`
      )
    }

    // 页面加载时获取数据
    onMounted(() => {
      loadActivityTypes()
      loadActivities()
    })
    
    return {
      loading,
      searchKeyword,
      filterType,
      filterStatus,
      filterPlatformType,
      dateRange,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      formData,
      activityTypes,
      activityPlatformTypes,
      filteredData,
      registrationDialogVisible,
      registrationLoading,
      registrationPage,
      registrationPageSize,
      registrationTotal,
      currentActivity,
      registrationData,
      getStatusType,
      getStatusText,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      showAddDialog,
      handleEdit,
      handleDelete,
      handleUploadSuccess,
      beforeUpload,
      handleSubmit,
      rules,
      handleRegistrations,
      confirmRegistration,
      cancelRegistration,
      rejectRegistration,
      checkIn,
      getStatusType,
      getStatusText,
      getRegistrationStatusType,
      getRegistrationStatusText,
      handleRegistrationSizeChange,
      handleRegistrationCurrentChange,
      hasPermission,
      handleApprove,
      uploadAction,
      uploadHeaders,
      loadActivities,
      exportExcel,
      exportRegistrationExcel,
      getPlatformTypeLabel
    }
  }
}
</script>

<style scoped>
.admin-activities {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.registration-header {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.registration-header h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.registration-header p {
  margin: 0;
  color: #666;
}

/* 图片上传样式 */
.upload-demo {
  display: inline-block;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  display: block;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>